package cn.rayland.androidkeyevent;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

/**
 * Created by gw on 2016/3/23.
 */
public class PowerKeyEventReceiver extends BroadcastReceiver {

    private OnPowerKeyListener onPowerKeyListener;
    private volatile long firstClickTime = 0;
    private volatile long secondClickTime = 0;

    public void setOnPowerKeyListener(OnPowerKeyListener listener){
        this.onPowerKeyListener = listener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(action.equals(Intent.ACTION_SCREEN_OFF) || action.equals(Intent.ACTION_SCREEN_ON)) {
            checkSingleOrDouble();
        }
        if(action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)){
            if(onPowerKeyListener!=null){
                onPowerKeyListener.onPowerKeyLongPressed();
            }
        }
        }

    /**
     * 判断单击还是双击，并回调方法
     */
    private void checkSingleOrDouble() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (firstClickTime != 0) {
                    secondClickTime = System.currentTimeMillis();
                    if (secondClickTime - firstClickTime < 500) {
                        secondClickTime = 0;
                        firstClickTime = 0;
                        if(onPowerKeyListener!=null){
                            onPowerKeyListener.onPowerKeyDoubleClick();
                        }
                    }
                } else {
                    firstClickTime = System.currentTimeMillis();
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (firstClickTime != 0) {
                        firstClickTime = 0;
                        secondClickTime = 0;
                        if(onPowerKeyListener!=null){
                            onPowerKeyListener.onPowerKeyClick();
                        }
                    }
                }
            }
        }).start();
    }

    // 回调接口
    public interface OnPowerKeyListener {
        void onPowerKeyClick();
        void onPowerKeyDoubleClick();
        void onPowerKeyLongPressed();
    }
}
